package api

import (
	"ginfast/app/system/dto"
	"ginfast/app/system/model"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/pkg/tree"
	"ginfast/util"
)

// Dept 部门
type Dept struct {
}

// ListHandler 列表
func (Dept) ListHandler(c *ginx.Context) {
	var p dto.Where
	if err := c.MustBind(&p); err != nil {
		return
	}
	var data []model.Dept
	p.DbModelWhere(&model.Dept{}).Find(&data)
	c.JSONWriteData(data)
}

// ListExcludeHandler 部门列表（排除节点）
func (Dept) ListExcludeHandler(c *ginx.Context) {
	// id, err := ctxQueryInt(c, "id")
	// if err != nil {
	// 	JSONP(StatusError).WriteTo(c)
	// }
	// where := fmt.Sprintf("id != %d", id)
	// var depts []model.Dept
	// orm.DbFindAll(where, depts, "order_num asc")
	c.JSONWriteData(nil)
}

// GetHandler 查询部门详细
func (Dept) GetHandler(c *ginx.Context) {
	util.QueryByID(&model.Dept{}, c)
}

// TreeSelectHandler 查询下拉树结构
func (Dept) TreeSelectHandler(c *ginx.Context) {
	var nodes []dto.Node
	err := orm.DB().Model(&model.Dept{}).Scan(&nodes).Error
	if err == nil {
		tree.Slice(nodes, func(i int) bool { return nodes[i].IsRoot(nodes) }, func(i1, i2 int) bool {
			return nodes[i1].ID == nodes[i2].ParentID
		})
	}
	c.JSONWriteData(nodes, err)
}

// RoleDeptTreeSelectHandler 根据角色ID查询树结构
func (Dept) RoleDeptTreeSelectHandler(c *ginx.Context) {
	c.JSONWriteData(nil)
}

func checkAddDept(s *model.Dept) error {
	if err := orm.DbFirstBy(&model.Dept{}, "Name LIKE ?", s.Name); err != nil {
		return err
	}
	return nil
}

// AddHandler 新增
func (Dept) AddHandler(c *ginx.Context) {
	var p model.Dept
	//获取参数p
	err := c.MustBind(&p)
	if err != nil {
		return
	}
	err = checkAddDept(&p)
	if err == nil {
		err = orm.DbCreate(&p)
	}
	c.JSONWriteError(err)
}

// UpdateHandler 修改
func (Dept) UpdateHandler(c *ginx.Context) {
	var p model.Dept
	err := c.MustBind(&p.DeptOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateModel(&p)
	c.JSONWriteError(err)
}

// DeleteHandler 删除
func (Dept) DeleteHandler(c *ginx.Context) {
	util.Deletes(&model.Dept{}, c)
}

func (o Dept) Routers(r *ginx.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/list/exclude/:id", o.ListExcludeHandler)
	r.GET("/:id", o.GetHandler)
	r.GET("/treeSelect", o.TreeSelectHandler)
	r.GET("/roleDeptTreeselect/:id", o.RoleDeptTreeSelectHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
